<template>
  <el-container>
    <el-aside class="sidebar">
      <el-scrollbar>
        <el-menu @select="handleMenuSelect" class="menu" :default-active="defaultActive">
          <div class="sidebar-header">
            <el-button type="primary" class="add-button" @click="openDialog">
              <el-icon style="vertical-align: middle">
                <Plus />
              </el-icon>
              <span style="vertical-align: middle"> 新建从站 </span>
            </el-button>
          </div>
          <!-- 动态生成菜单项 -->
          <el-menu-item
            v-for="route in menuRouter.getRoutes().filter((r) => r.path !== '/')"
            :key="route.path"
            :index="route.path"
          >
            <!-- 左侧菜单内容 -->
            <div class="menu-item-left">
              <el-icon>
                <component :is="Warning" />
              </el-icon>
              <span>{{ route.name }}</span>
            </div>
            <!-- 右侧操作按钮 -->
            <div class="menu-item-right">
              <el-button type="text" size="small" @click.stop="handleEdit(route)">
                <el-icon>
                  <Edit />
                </el-icon>
              </el-button>
              <el-button type="text" size="small" @click.stop="handleDelete(route)">
                <el-icon>
                  <Delete />
                </el-icon>
              </el-button>
            </div>
          </el-menu-item>
        </el-menu>
      </el-scrollbar>
    </el-aside>

    <AddConnection
      :dialogVisible="dialogVisible"
      :setDialogVisible="setDialogVisible"
      @addSuccess="addSuccess"
    />
    <EditConnection
      ref="editConnectionRef"
      :device="device"
      @update:device="updateDevice"
      @editDeviceSuccess="editDeviceSuccess"
    />

    <el-container>
      <el-main>
        <el-scrollbar>
          <router-view />
        </el-scrollbar>
      </el-main>
    </el-container>
  </el-container>
</template>

<script lang="ts" setup>
import { useRoute, useRouter } from "vue-router";
import menuRouter from "@/router/index";
import { Delete, Edit, Warning } from "@element-plus/icons-vue";
import { onMounted, ref, watch } from "vue";
import AddConnection from "@/components/AddConnection.vue";
import type { Device } from "@/types/device";
import EditConnection from "@/components/EditConnection.vue";
import { useDeviceStore } from "@/stores/device.ts";
import { ElMessage, ElMessageBox } from "element-plus";
import { deleteDevice as deleteDeviceApi } from "@/api/deviceApi.ts";

const router = useRouter();
const defaultActive = ref("/");
const dialogVisible = ref(false);
const editConnectionRef = ref<typeof EditConnection>();
const route = useRoute();
const routeName = ref(route.name as string);
const deviceStore = useDeviceStore();
const device = ref<Device>({
  id: 0,
  name: "",
  ip: "127.0.0.1",
  port: 502,
  protocol: "Tcp",
  isConnected: false,
});

const editDeviceSuccess = async (
  deviceName: string,
  ip: string,
  port: number,
  protocol: string
) => {
  device.value.name = deviceName;
  device.value.ip = ip;
  device.value.port = port;
  device.value.protocol = protocol;
  location.reload();
  router.push(deviceName);
};

const updateDevice = (newDevice: Device) => {
  device.value = newDevice;
};

const handleEdit = async (route: any) => {
  const editDevice: Device = await deviceStore.getDevice(route.name as string);
  editConnectionRef.value?.setDevice(editDevice);
  editConnectionRef.value?.openDialog();
};

const handleDelete = async (route: any) => {
  const deleteDevice: Device = await deviceStore.getDevice(route.name as string);
  // 弹出对话框确认是否要删除
  await ElMessageBox.confirm(`确定要删除设备 ${deleteDevice.name} 吗？`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  });
  const isSuccess = await deleteDeviceApi(deleteDevice.name);
  if (isSuccess) {
    ElMessage({
      type: "success",
      message: `设备${deleteDevice.name}删除成功!`,
      duration: 3000,
    });
    location.reload();
  } else {
    ElMessage({
      type: "error",
      message: `设备${deleteDevice.name}删除失败!`,
      duration: 3000,
    });
  }
};

const handleMenuSelect = (path: string) => {
  // 保存选中的路由到 localStorage
  localStorage.setItem("activeRoute", path);
  // 导航到选中的路由
  router.push(path);
};

function setDialogVisible(value: boolean) {
  dialogVisible.value = value;
}

const openDialog = () => {
  dialogVisible.value = true;
};

const addSuccess = async () => {
  location.reload();
};

watch(
  () => route.name,
  async (newRouteName) => {
    if (newRouteName) {
      routeName.value = newRouteName as string;
      device.value = await deviceStore.getDevice(routeName.value);
    }
  }
);

onMounted(() => {
  // 从 localStorage 中恢复选中的路由
  const savedActive = localStorage.getItem("activeRoute");
  if (savedActive) {
    defaultActive.value = savedActive;
  }
  // 确保页面加载时导航到默认路由
  router.push(defaultActive.value);
});
</script>

<style scoped lang="scss">
.el-container {
  padding: 0;
  margin: 0;
  width: 100%;
  height: 100vh; /* 确保占满视口 */
}

.menu-item-container {
  display: flex;
  align-items: center;
  width: 100%;
  height: 100%;
  /* 移除 justify-content: space-between 避免冲突 */
}

.menu-item-left {
  display: flex;
  align-items: center;
  flex-shrink: 0; /* 防止被压缩 */
  white-space: nowrap; /* 强制不换行 */
  overflow: hidden; /* 隐藏溢出内容 */
  text-overflow: ellipsis; /* 显示省略号 */
  max-width: 60%; /* 限制宽度（需根据实际布局调整） */
}

.menu-item-right {
  display: flex;
  align-items: center;
  margin-left: auto; /* 强制右对齐 */
  padding-left: 4px; /* 替代gap的间距效果 */
  height: 100%;
}

/* 覆盖Element UI按钮默认样式 */
.menu-item-right .el-button {
  margin-left: 0 !important; /* 清除按钮默认外边距 */
  padding: 0 0 !important; /* 压缩按钮内边距 */
  min-width: auto !important; /* 取消最小宽度限制 */
}

.el-menu-item {
  padding: 0 10px !important; /* 完全清除内边距 */
  min-height: 40px;
  display: flex;
  align-items: center;
}

.el-aside {
  height: 100vh;
  width: auto;
}

.el-main {
  padding: 0;
  margin: 0 0 0 0;
}

.sidebar {
  width: auto;
  height: 100vh;
  background-color: #f8f9ff;
}

.sidebar-header {
  text-align: center;
  margin-top: 20px;
  margin-bottom: 10px;

  :deep(.add-button) {
    width: 120px;
    height: 40px;
  }
}

.sidebar-header h1 {
  margin: 0;
  font-size: 1.5em;
  color: #333;
}

/* el-scrollbar 样式调整 */
.el-scrollbar {
  height: 100%; /* 让 el-scrollbar 占满侧边栏高度 */
}

.el-scrollbar__wrap {
  overflow-x: hidden; /* 隐藏横向滚动条 */
}

/* 选中效果 */
.el-menu-item.is-active {
  background-color: #dbeafe !important; /* 浅蓝色 */
  color: #333 !important;
}

.menu {
  width: 200px;
  border-right: none;
  background-color: transparent;
}

.borderless-button {
  border: none;
  background-color: transparent;
  font-size: 20px;
  margin-right: 5px;
  /* 其他你需要的样式 */
}
</style>
